package uno.linze.interview_question.util;

import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uno.linze.interview_question.util.base.RedisUtil;

import java.util.Random;

@Service
public class VerificationCodeService {
    @Autowired
    EmailService emailService;

    private final RedisUtil redisUtil;

    // 验证码有效期，单位：秒 (5天)
    private static final long VERIFICATION_CODE_EXPIRATION = 5 * 24 * 60 * 60;

    public VerificationCodeService(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 生成并保存6位数字验证码
     *
     * @param email 邮箱地址，作为 Redis 的唯一键
     * @return 生成的验证码
     */
    public String saveVerificationCode(String email) throws MessagingException {
        // 生成一个6位数字验证码
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        String verificationCode = String.valueOf(code);

        // 将验证码存入 Redis，并设置有效期为5天
        redisUtil.set(email, verificationCode, VERIFICATION_CODE_EXPIRATION);

        System.out.println("为邮箱 " + email + " 生成并保存了验证码：" + verificationCode);
        emailService.sendVerificationCodeEmail(email, verificationCode);

        return verificationCode;
    }

    /**
     * 根据邮箱获取验证码
     *
     * @param email 邮箱地址
     * @return 验证码，如果不存在则返回 null
     */
    public String getVerificationCode(String email) {
        Object code = redisUtil.get(email);
        if (code != null) {
            System.out.println("从 Redis 中找到了邮箱 " + email + " 的验证码：" + code.toString());
            //删除验证码，确保只能使用一次
            redisUtil.del(email);
            return code.toString();
        }
        System.out.println("Redis 中不存在邮箱 " + email + " 的验证码");
        return null;
    }
}
